extends ../layout

include ./admin-mixins.pug

block headContent
	title OS Stats

block content
	+adminNav("OS Stats")

	
	+pageTitle("OS Stats")

	.clearfix
		.row
			each itemName in appStatNames
				.col-lg-6.float-start
					+contentSection(itemName)
						canvas(id=`canvas-${itemName}`)


block endOfBody

	+graphPageScriptSetup(true)
	

	script.
		var appStatNames = !{JSON.stringify(appStatNames)};
		var appStats = !{JSON.stringify(appStats)};

		var graphsById = {};

		$(document).ready(function() {
			var blue = "#007bff";

			for (var n = 0; n < appStatNames.length; n++) {
				var propName = appStatNames[n];

				var data = [];
				for (var i = 0; i < appStats[propName].length; i++) {
					var item = appStats[propName][i];

					data.push({x:new Date(item.time), y:item.value});
				}

				console.log(propName + " - " + JSON.stringify(data));

				createGraph(`canvas-${propName}`, [propName], [data], [blue]);
			}
		});

		function createGraph(chartid, names, datas, colors) {
			var datasets = [];
			var yaxes = [];

			for (var i = 0; i < names.length; i++) {
				datasets.push({
					label: names[i],
					data: datas[i],
					borderWidth: 1,
					borderColor: colors[i],
					backgroundColor: 'rgba(0, 0, 0, 0)',
					pointRadius: 1,
					lineTension: 0
				});

				yaxes.push({
					scaleLabel: {
						display: false,
						//labelString: names[i]
					},
					grid: {
						color: gridLineColor
					},
				});
			}

			// update data in graph if we already created, otherwise create anew
			if (graphsById[chartid]) {
				graph = graphsById[chartid];
				graph.data = { datasets: datasets };
				graph.update();

			} else {
				var ctx = document.getElementById(chartid).getContext('2d');
				var graph = new Chart(ctx, {
					type: 'line',
					data: {
						datasets: datasets
					},
					options: {
						// disable all animations
						animation: { duration: 0 },
						hover: { animationDuration: 0 },
						responsiveAnimationDuration: 0,

						legend: {
							display: (datasets.length > 1)
						},
						scales: {
							x: {
								type: 'time',
								position: 'bottom',
								time: {
									unit: 'hour'
								},
								scaleLabel: {
									display: true,
									labelString: 'Time'
								},
								grid: {
									color: gridLineColor
								},
							},
							y: {
								type: 'linear',
								position: 'left',
								scaleLabel: {
									display: false,
								},
								grid: {
									color: gridLineColor
								},
							},
						}
					}
				});

				graphsById[chartid] = graph;
			}
		}
